package com.jh.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jh.constant.JwtClaimsConstant;
import com.jh.properties.JwtProperties;
import com.jh.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始插入时公共字段自动填充");

        Long currentId = getCurrentUserIdFromToken();

        // 动态检查字段存在性，适配 order_detail 等表
        if (metaObject.hasSetter("createUser")) {
            this.strictInsertFill(metaObject, "createUser", Long.class, currentId);
            log.debug("填充 createUser: {}", currentId);
        }
        if (metaObject.hasSetter("updateUser")) {
            this.strictInsertFill(metaObject, "updateUser", Long.class, currentId);
            log.debug("填充 updateUser: {}", currentId);
        }
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            log.debug("填充 createTime");
        }
        if (metaObject.hasSetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            log.debug("填充 updateTime");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始更新时公共字段自动填充");

        Long currentId = getCurrentUserIdFromToken();

        if (metaObject.hasSetter("updateUser")) {
            this.strictUpdateFill(metaObject, "updateUser", Long.class, currentId);
            log.debug("填充 updateUser: {}", currentId);
        }
        if (metaObject.hasSetter("updateTime")) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            log.debug("填充 updateTime");
        }
    }

    private Long getCurrentUserIdFromToken() {
        try {
            // 通过 RequestContextHolder 获取请求
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                log.warn("无 Web 上下文，使用默认用户 ID");
                return 1L; // 默认用户 ID
            }
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(jwtProperties.getAdminTokenName());
            if (token == null || token.isEmpty()) {
                log.warn("Token 为空，使用默认用户 ID");
                return 1L; // 默认用户 ID
            }
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.debug("解析 Token 成功，userId: {}", userId);
            return userId;
        } catch (Exception e) {
            log.error("解析 Token 失败，使用默认用户 ID", e);
            return 1L; // 默认用户 ID
        }
    }
}